package com.yima.baseproj.module.sys.role.menu;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysRoleMenuService extends ServiceImpl<SysRoleMenuMapper, SysRoleMenuEntity> {

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Transactional
    public void saveRoleMenu(String roleId, List<String> menuIdList) {
        //删除
        removeByMap(MapUtil.<String,Object>builder()
                .put("role_id",roleId)
                .build());

        if(CollectionUtil.isNotEmpty(menuIdList)){
            List<SysRoleMenuEntity> list = CollectionUtil.newArrayList();
            for (String menuId : menuIdList) {
                SysRoleMenuEntity sysRoleMenu = new SysRoleMenuEntity();
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenu.setMenuId(menuId);
                list.add(sysRoleMenu);
            }
            saveBatch(list);
        }
    }

    public void deleteByRoleId(String roleId) {
        removeByMap(MapUtil.<String,Object>builder()
                .put("role_id",roleId)
                .build());
    }

    public void deleteByMenuId(String menuId) {
        removeByMap(MapUtil.<String,Object>builder()
                .put("menu_id",menuId)
                .build());
    }

    public List<String> findMenuIdListByRoleId(String roleId) {
        List<SysRoleMenuEntity> list = baseMapper.selectByMap(MapUtil.<String,Object>builder()
                .put("role_id",roleId)
                .build());
        return list.stream().map(item->item.getMenuId()).collect(Collectors.toList());
    }
}
